// pages/contest/index/index.js
import api from '../../../api/index'
import IMService from '../../../static/lib/imservice.js';
import user from "../../../api/user"
import store from "../../../store/index"

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
      pageNumber: 1,
      contestItems: [
        {cover: '/images/华农1.jpg',
         title: '丁颖杯发明创意大赛',
         endTime: '04-30'},
         {cover: '/images/华农2.jpg',
         title: '创客杯创客杯创客杯我的看看我是谁大学生创业大赛',
         endTime: '04-22'},
         {cover: '/images/华农2.jpg',
         title: '创客杯创客杯创客杯我的看看我是谁大学生创业大赛',
         endTime: '04-22'},
         {cover: '/images/华农2.jpg',
         title: '创客杯创客杯创客杯我的看看我是谁大学生创业大赛',
         endTime: '04-22'},
      ],
      endContest:[],
      activeIndex: 0,
      switchList:[],
      sortList: ['正在报名', '已结束'],
      type:"all",
      status:"ing",
      show:true,
      contest:{
        name:"华农花海摄影大赛",
        title:"在限定的花期里留下永恒的美照",
        switch:0,
        timeEnd:"2022-03-24",
        type:"create",
        detail:"拥有善于发现美的眼睛，能够拍摄出一张花花的照片",
        rule:"一等奖：华农限定戒指；二等奖：华农限定明信片；三等奖：华农酸奶",
        url:"",
        status:"ing",
        introduction:"希望华农er们多多拍照，踊跃参赛，让别人知道华南赏花大学的称号不是盖的"  ,
        images:[],  
      },
      allShow: true, 
      loading: true,
  },

  test: function() {
    this.authGetSend6();
    
  },

  //获取授权的点击事件
  authGetSend6() {
    const that = this;

    wx.requestSubscribeMessage({
      tmplIds: ['ugZ6EmGdfoc00XIb7kB5mROhg1HFFzBLAble6O6XTyc'], //这里填入我们生成的模板id
      success(res) {
        console.log('授权成功', res);
        that.getOpenid().then(res => {
          console.log('获取id为：' + res);
          that.send6(res, '666');
        });
        
      },
      fail(res) {
        console.log('授权失败', res)
      }
    })
  },
  //获取用户的openid
  getOpenid() {
    return new Promise((resolve, reject) => {//promise风格，请求同步化
      wx.cloud.callFunction({
        name: "login"
      })
        .then(res => {
          let openid = res.result.openid
          console.log("获取openid成功", openid)
          resolve(openid);//返回openid
        }).catch(err => {
          console.log("获取openid失败", err)
          reject(err);//返回错误信息
        })
    })

  },
  //发送模板消息到指定用户,推送之前要先获取用户的openid,和内容
   send6(openid, sendContent) {
    wx.cloud.callFunction({
      name: 'subscribe',
      data: {
        action: 'send6', //定义属性action,值为send6字符串
        // sendContent:sendContent,
        // {//推送的内容
          thing1: 'Smooth',//需要传给模板的参数
          thing2: '有人找你聊天啦',//需要传给模板的参数
          time3:"2020年11月17日 15:00",
        // },//发送给模板的封装好的json内容
        openid: openid
      }
    }).then(res => {
      console.log("推送消息成功", res)
    }).catch(err => {
      console.log("推送消息失败", err)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  
  async onLoad(options) {
    wx.hideTabBar();
    this.teamList();
   //this.publish()
    api.contest.switchList().then(res=>{
      // console.log(res.data);
      this.setData({
       switchList:res.data.list
      })
    })
    this.getCurr();
    const load = setInterval(() => {
      if(this.data.contestItems && this.data.endContest && this.data.switchList && this.data.listShow) {
        // 全部数据获取完成，允许页面展现
        // this.setData({
        //   allShow: true
        // });
        this.setData({
          loading: false,
        });
        wx.showTabBar();
        clearInterval(load);
      }
    },1000)
  },

  onShow () {
		this.getCurr()
	},
  getCurr: async function(){
    var currentUserId= app.globalData.openid;
	 var currentUser = {
		uuid: '',
		avatar: '',
		name: ''
	 }
	 await user.getAvatar(currentUserId).then(res => {
		currentUser.uuid = currentUserId
		currentUser.avatar = res.data.avatarUrl
		currentUser.name = res.data.nickName
	})
    app.globalData.imService= new IMService(wx.im);
    app.globalData.imService.connectIM(currentUser);
    if(wx.im.getStatus() === 'disconnected') {
			app.globalData.imService= new IMService(wx.im);
			app.globalData.imService.connectIM(currentUser);
    }

    let self = this;
		wx.im.on(wx.GoEasyIM.EVENT.CONVERSATIONS_UPDATED, (conversations) => {
			// 设置tabBar未读消息总数以及conversation
			self.setConversations(conversations);
		});
	//加载会话列表
  wx.im.latestConversations()
  .then(res => {
    let content = res.content;
    self.setConversations(content);
   this.setData({
    showLoading:false,
    listShow:true
   })
  })
  .catch(e => {
    console.log(e);
    wx.hideLoading();
  });
   },
  onPullDownRefresh () {
    wx.showNavigationBarLoading()
    console.log('下拉刷新');
     this.teamList()
     wx.hideNavigationBarLoading() //完成停止加载
     wx.stopPullDownRefresh() //停止下拉刷新
  },

  publish:function(){
    const params = this.data.contest
    api.contest.publish(params).then(res=>{
      console.log(res)
    })
  },
  setConversations (conversations) {
		conversations.conversations && conversations.conversations.map((item) => {
			// 格式化时间格式
			item.lastMessage.date = app.formatDate(item.lastMessage.timestamp)
		});
		this.setData({
			conversations : conversations.conversations
		},()=>{
				console.log(this.data.conversations)
		}

		);
		this.setUnreadAmount(conversations.unreadTotal);
  },
	setUnreadAmount(unreadTotal) {
		if(unreadTotal >0){
			wx.setTabBarBadge({
				index: 2,
				text: unreadTotal.toString()
			});
		}else{
			wx.hideTabBarRedDot({
				index :0
			});
		}
	},
  list:function(){
    const type = this.data.type
    const status = "ing"
    const params = {type,status}
    api.contest.list(params).then(res=>{
      console.log("正在进行中的比赛：")
      console.log(res);
      store.contestList = res.data.list;
      this.setData({
        contestItems:res.data.list
     })
    })
  },
  list2:function(){
    const type = this.data.type
    console.log("已经结束的比赛：")
    const status = "end"
    const params = {type,status}
    api.contest.list(params).then(res=>{
      console.log(res)
      this.setData({
        endContest:res.data.list
     })
    })
  },
  
  teamList:async function(){
    return new Promise((resolve,reject)=>{
      const t1 = this.list()
      const t2 = this.list2()
      resolve({t1,t2})
    })
  },
  del:function(){
    var id = '28ee4e3e606e95e10e899f2508b4a230'
    var params = {id}
    api.contest.del(params).then(res=>{
      console.log(res)
    })
  },
  edit:function(){
    var id = this.data.id
    var contest = this.data.contest
    var params= {id,contest}
    console.log(params)
    api.contest.edit(params).then(res=>{
      console.log(res)
    })
  },

  // 修改分类
  tapSort: function(e) {
    const that = this
    var activeIndex = e.currentTarget.dataset.index;
    if (activeIndex == this.data.activeIndex) return;
    this.setData({
        activeIndex,
        status:this.data.activeIndex==0?"end":"ing",
        pageNumber: 1
    });
  },
  tapTask: function(e) {
    var index =  e.currentTarget.dataset.index
    console.log(index)
    var contest = this.data.contestItems[index]
    wx.navigateTo({
      url: '../detail/detail?contest='+ encodeURIComponent(JSON.stringify(contest)),
    })
  },
  tapEndTask: function(e) {
    var index =  e.currentTarget.dataset.index
    console.log(index)
    var contest = this.data.endContest[index]
    wx.navigateTo({
      url: '../detail/detail?contest='+JSON.stringify(contest)+'&id='+"404",
    })
  },
  tapSearch: function() {
    wx.navigateTo({url: '/pages/search/search'})
  },

  // 分享给朋友
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '玩转组队'
        })
      }, 2000)
    })
    return {
      title: '玩转组队',
      path: '/pages/contest/index/index',
      promise 
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title:'玩转组队',
      imageUrl:'../../../images/wzhn.jpg'
    }
  }
})
